<?php

/**
 * This is the model class for table "crops".
 *
 * The followings are the available columns in table 'crops':
 * @property integer $id
 * @property integer $group_id
 * @property string $variety
 * @property string $type
 * @property integer $is_active
 *
 * The followings are the available model relations:
 * @property Groups $group
 * @property Prices[] $prices
 */
class Crop extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Crop the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'crops';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('type, variety', 'required'),
            array('type, variety', 'length', 'max' => 50),
            array('type, variety', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'group' => array(self::BELONGS_TO, 'Group', 'group_id'),
            'prices' => array(self::HAS_MANY, 'Price', 'crop_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'group_id' => 'Group',
            'variety' => 'Crop Variety',
            'type' => 'Crop Type',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {

        $criteria = new CDbCriteria;
        
        $criteria->compare('variety', $this->variety, true);
        $criteria->compare('type', $this->type, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function beforeSave() {
        if ($this->isNewRecord) {
            $this->group_id = Yii::app()->user->instance->group_id;
            $this->type = strtolower($this->type);
        }

        return parent::beforeSave();
    }
    
    public function getLastPrice($cropId) {
        $sql = 'SELECT amount FROM prices where crop_id = :cropId ORDER BY effective_date DESC LIMIT 1';

        $command = Yii::app()->db->createCommand($sql);
        $command->bindParam(':cropId', $cropId, PDO::PARAM_INT);
        $result = $command->queryRow();
        
        return $result['amount'];
    }
    
    public function getLastPriceUpdate($cropId) {
        $sql = 'SELECT timestamp FROM prices where crop_id = :cropId ORDER BY effective_date DESC LIMIT 1';

        $command = Yii::app()->db->createCommand($sql);
        $command->bindParam(':cropId', $cropId, PDO::PARAM_INT);
        $result = $command->queryRow();
        
        return ($result['timestamp'] != null) ? $result['timestamp'] : null;
    }

    public function scopes() {
        return array(
            'active' => array(
                'condition' => 'is_active=1',
            ),
        );
    }

    public function defaultScope() {
        return array(
            'condition' => 'group_id=' . Yii::app()->user->instance->group_id,
            'order' => 'type,variety ASC'
        );
    }

}